import { defineStore } from 'pinia'
import { ref } from 'vue'
// import defaultSettings from '@/settings'
import { getConfig, getLoginConfig, getAllConfig } from '@/api/system/config'
import { getPlaid } from '@/utils/auth'

// const { fixedHeader, sidebarLogo } = defaultSettings

export const useSettingsStore = defineStore('settings', () => {
  // state
  const login = ref({})
  const site = ref({})
  const customer = ref({})
  const hooks = ref({})
  const hooksLoading = ref(true)
  const fixedHeaderRef = ref(true)
  const sidebarLogoRef = ref(true)

  // actions
  const setSetting = (obj) => {
    if (obj.key === 'customer') {
      customer.value = obj.data
    }
  }

  const setAllSetting = (data) => {
    login.value = data.login || {}
    site.value = data.site || {}
    hooks.value = data.hooks || {}
    hooksLoading.value = false
  }

  const setHooks = (hookData) => {
    hooks.value = hookData
  }

  const setHooksLoading = (loading) => {
    hooksLoading.value = loading
  }

  const setLogin = (data) => {
    login.value = data
  }

  // 获取登录配置
  const getLogin = () => {
    return new Promise((resolve, reject) => {
      getLoginConfig()
        .then((response) => {
          const { data } = response
          setLogin(data)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取单个配置
  const getSetting = (key) => {
    return new Promise((resolve, reject) => {
      getConfig(key)
        .then((response) => {
          const { data } = response
          setSetting({ key, data })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取所有配置
  const getAllSetting = () => {
    return new Promise((resolve, reject) => {
      hooksLoading.value = true
      const plaid = getPlaid()

      getAllConfig({
        dkSys: {
          plaid
        }
      })
        .then((response) => {
          const { data } = response
          setAllSetting(data)
          resolve(data)
        })
        .catch((error) => {
          hooksLoading.value = false
          reject(error)
        })
    })
  }

  return {
    login,
    site,
    customer,
    hooks,
    hooksLoading,
    fixedHeader: fixedHeaderRef,
    sidebarLogo: sidebarLogoRef,
    setSetting,
    setAllSetting,
    setHooks,
    setHooksLoading,
    setLogin,
    getLogin,
    getSetting,
    getAllSetting
  }
})
